//
//  UNTabBarController.swift
//  Unibet
//
//  Created by HaoSheng on 2020/4/14.
//  Copyright © 2020 蜗牛. All rights reserved.
//

import UIKit
import simd
///自定义TabBarController
open class UNTabBarController: UITabBarController,UITabBarControllerDelegate {
    
    public var titleColor: UIColor = .FromHex(rgb: 0x333333)
    public var titleSelectColor: UIColor = .blue
    
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        self.delegate = self
        
        
        view.backgroundColor = .white
//        //利用KVC替换默认的TabBar
//        self.setValue(myTabBar, forKey: "tabBar")
        
        //设置背景色
        self.tabBar.barTintColor = .white
        
        //设置TabBar不透明,解决在透明时nav pop回来时 item图标的错位移动问题
        self.tabBar.isTranslucent = false
        
        
        
//        let fpsLab = YYFPSLabel.init()
//        fpsLab.frame = .init(x: 100, y: 100, width: 100, height: 30)
//        fpsLab.sizeToFit()
//        self.view.addSubview(fpsLab)
        
        getMessageNum()
        
        
    } 
    
    public let messageIndex = 3
    ///获取消息数量
    public func getMessageNum(){
    }
    
    
    ///添加子控制器
    open func addChilVC(childVC: UIViewController,Title: String ,imageName: String ){
        
        setChilVCItem(childVC: childVC, Title: Title, imageName: imageName)
        
        let nav = UNNavigationController(rootViewController: childVC)
        self.addChild(nav)
    }
        
    ///设置Item
    public func setChilVCItem(childVC: UIViewController,Title: String ,imageName: String){
        
        childVC.tabBarItem.title = Title
        
        childVC.tabBarItem.image = UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal)
        childVC.tabBarItem.selectedImage = UIImage(named: imageName + "_select" )?.withRenderingMode(.alwaysOriginal)
        
        childVC.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: titleColor], for: .normal)
        childVC.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:titleSelectColor], for: .selected)
        
    }
    
    ///更换子控制器
    public func replaceChilVC(childVC: UNNavigationController,Title: String ,imageName: String,objectAtIndex:Int){
        
        if childVC.viewControllers.count > 0 {
            setChilVCItem(childVC: childVC.viewControllers.first!, Title: Title, imageName: imageName)
        }
        
        var vcs:[UIViewController] = []
        for i in 0...viewControllers!.count - 1 {
            if i == objectAtIndex {
                vcs += [childVC]
            }else{
                vcs += [viewControllers![i]]
            }
        }
        
        setViewControllers(vcs, animated: false)
        
    }
    
    
    
    // 将要切换Tab
    public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        let title = tabBarController.tabBar.selectedItem?.title
        if title == "消息" {
        }
        return true
    }
        
    // 点击TabBar
    public override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        
        //TODO: 适配IOS26，不需要这个动画
        
        var arry: [UIView] = []

        let tempItems = tabBar.items! as NSArray
        let index = tempItems.index(of: item)
        var tabBars = tabBar.subviews
        //根据子view的x坐标排序
        tabBars = tabBars.sorted { viewOne, viewTwo in
            return viewOne.frame.origin.x < viewTwo.frame.origin.x
        }
        for btn in tabBars {
            if btn.isKind(of: NSClassFromString("UITabBarButton")!) {
                arry += [btn]
            }
        }
        
        //添加动画
        //放大效果，并回到原位
        let animation = CABasicAnimation.init(keyPath: "transform.scale")
        //速度控制函数，控制动画运行的节奏
        animation.timingFunction = CAMediaTimingFunction.init(name: .easeInEaseOut)
        animation.duration = 0.1    //执行时间
        animation.repeatCount = 1   //执行次数
        animation.autoreverses = true   //完成动画后会回到执行动画之前的状态
        animation.fromValue = 1     //初始伸缩倍数
        animation.toValue = 1.2     //结束伸缩倍数
        arry[index].layer.add(animation, forKey: nil)
        
        
    }
    
    
    
    
    
    
    
}




extension UITabBar {
    /**
     添加小红点

     - parameter index: index
     */
    public func showBadgeOnItemIndex(index : Int,num:Int){
        // 移除之前的小红点
        removeBadgeOnItemIndex(index: index)
        // 新建小红点Autoshrink
        let badgeView = UILabel.init()
        badgeView.text = num < 99 ? num.description : 99.description
        badgeView.textAlignment = .center
        badgeView.font = UIFont.systemFont(ofSize: 12)
        badgeView.textColor = .white
        badgeView.backgroundColor = .red
        badgeView.tag = 888 + index
        badgeView.layer.cornerRadius = 5
        badgeView.backgroundColor = UIColor.red
        let tabFrame = self.frame
        // 确定小红点的位置
        let percentX = (Double(index) + 0.6) / Double(items?.count ?? 4)
        let x = ceilf(Float(percentX) * Float(tabFrame.size.width) - 5)
        let y = ceilf(0.05 * Float(tabFrame.size.height))
        
        badgeView.frame = .init(x: CGFloat(x), y: CGFloat(y), width: num > 9 ? 23 : 18, height: num > 9 ? 20 : 18)
        badgeView.layer.cornerRadius = badgeView.frame.size.height/2
        badgeView.layer.masksToBounds = true
        self.addSubview(badgeView)
    }

    public func hideBadgeOnItemIndex(index : Int){
        // 移除小红点
        removeBadgeOnItemIndex(index: index)
    }
    public func removeBadgeOnItemIndex(index : Int){
        // 按照tag值进行移除
        for itemView in self.subviews {
            if(itemView.tag == 888 + index){
                itemView.removeFromSuperview()
            }
        }
    }
}

